package me.zhengjie.modules.enrstu.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class EasyExcelListenerData<E> extends AnalysisEventListener<E> {
    private static final int BATCH_COUNT = 664487;
    private List<E> list = new ArrayList<>();
    private ListenerDataReturn<E> dataReturn;

    public EasyExcelListenerData(ListenerDataReturn<E> callback) {
        this.dataReturn = callback;
    }

    public EasyExcelListenerData() {
    }

    @Override
    public void invoke(E e, AnalysisContext analysisContext) {
        list.add(e);

        if (list.size() >= BATCH_COUNT) {
            saveData();
            list = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        dataReturn.onDataReady(list);
        log.info("存储数据库成功！");

    }
}
